<?php
/**
 * 新版v2栏目
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/12/4 15:09
 */
\ns_core\m_load::load("ns_data_model.m_data_model");
\ns_core\m_load::load_old("nn_logic/depot/depot_v2.class.php");
\ns_core\m_load::load_old("nn_logic/carrier/carrier.class.php");
class m_category_v2_inout  extends m_data_model
{
    /**
     * xml的 属性参数
     * @var unknown
     */
    public $arr_fileds = array(
        'nns_id'=>'id',
        'nns_name'=>'name',
        'nns_parent_id'=>'parent',
        'nns_import_category_id'=>'import_id',
        'nns_cp_id'=>'cp_id',
        'nns_import_parent_category_id'=>'parent_import_id',
    );
    /**
     * 添加参数检查模板
     * @var unknown
     */
    public $add_params  = array(
        'base_info'     =>      array(
            'nns_name'                      =>      array (
                'rule'      => 'noempty',
                'default'   => '',
                'length'    => '1-64',
                'desc'      => '栏目名称',
            ),
            'nns_category_id'               =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '0-32',
                'desc'      => '播控栏目id',
            ),
            'nns_parent_id'                 =>      array (
                'rule'      => '',
                'default'   => '0',
                'length'    => '0-32',
                'desc'      => '播控栏目父级id',
            ),
            'nns_depot_id'                  =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '0-32',
                'desc'      => '媒资库ID',
            ),
            'nns_org_id'                    =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '0-32',
                'desc'      => '媒资来源ID',
            ),
            'nns_cp_id'                     =>      array (
                'rule'      => 'noempty',
                'default'   => '',
                'length'    => '1-32',
                'desc'      => 'cp_id',
            ),
            'nns_order'                     =>      array (
                'rule'      => 'int',
                'default'   => '0',
                'length'    => '0-11',
                'desc'      => '权重',
            ),
            'nns_type'                      =>      array (
                'rule'      => 'tinyint',
                'default'   => '0',
                'length'    => '',
                'desc'      => '点/直播标志位 0点播 1直播',
            ),
            'nns_import_category_id'        =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '0-128',
                'desc'      => '第三方栏目ID',
            ),
            'nns_import_parent_category_id' =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '0-128',
                'desc'      => '第三方栏目ID',
            ),
        ),
        'hide_info'     => array(
            'nns_id' =>          array(
                'rule'      => 'noempty',
                'default'   => 'GUID',
                'length'    => '32',
                'desc'      => '栏目唯一id',
            ),
        )
    );

    /**
     * 删除参数检查模板
     * @var unknown
     */
    public $del_params  = array(
        'base_info'     =>      array(
            'nns_name'                      =>      array (
                'rule'      => 'noempty',
                'default'   => '',
                'length'    => '1-20',
                'desc'      => '栏目名称',
            ),
            'nns_import_category_id'        =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '0-128',
                'desc'      => '第三方栏目ID',
            ),
            'nns_cp_id'                     =>      array (
                'rule'      => 'noempty',
                'default'   => '',
                'length'    => '1-32',
                'desc'      => 'cp_id',
            ),
            'nns_type'                      =>      array (
                'rule'      => 'tinyint',
                'default'   => '0',
                'length'    => '',
                'desc'      => '影片类型 0 点播 | 1 直播',
            ),
            'nns_id'                        =>      array (
                'rule'      => '',
                'default'   => '',
                'length'    => '',
                'desc'      => '平台自身的ID',
            ),
        ),
    );
    /**
     * 检查注入参数
     * @param array $in_params 注入参数
     * @param string $action 操作参数行为
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因')
     * @author liangpan
     * @date 2016-03-12
     */
    public function check_input_params($in_params,$action)
    {
        $notice_params = $last_params = array ();
        $str_params = "{$action}_params";
        if (!isset($this->$str_params))
        {
            return $this->_return_data(1, '没有设置' . $str_params . '参数的判断模式');
        }
        if (!is_array($this->$str_params))
        {
            return $this->_return_data(1, '参数非数组');
        }
        return $this->_check_input_params($this->$str_params, $in_params,'message_queue');
    }

    /**
     * 主媒资模板导出
     * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')|multitype:number
     */
    public function export()
    {
        return self::return_data(0,'ok',array('add_params'=>$this->add_params,'edit_params'=>$this->edit_params,'del_params'=>$this->del_params));
    }

    /**
     * 添加栏目数据
     * @param array $params 添加数据 不能为空
     * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')|multitype:number
     */
    public function add($params)
    {
        //注入参数检查，模板参考
        $check_input_params = $this->check_input_params($params,'add');
        if($check_input_params['ret'] !=0)
        {
            return $check_input_params;
        }
        if(!isset($check_input_params['data_info']['info']['out']) || empty($check_input_params['data_info']['info']['out']) || !is_array($check_input_params['data_info']['info']['out']))
        {
            return self::return_data(1,'主媒资参数检查反馈数据为空');
        }
        $params = $check_input_params['data_info']['info']['out'];
        $result_cp = m_config::_get_cp_info($params['base_info']['nns_cp_id']);
        if($result_cp['ret'] !=0)
        {
            return $result_cp;
        }
        if(!isset($result_cp['data_info']) || !is_array($result_cp['data_info']) || empty($result_cp['data_info']))
        {
            return self::return_data(1,'未查询到CP信息，不执行 栏目创建');
        }
        //查询运营商
        $result_carrier = $this->query_carrier();
        if($result_carrier['ret'] !=0)
        {
            return $result_carrier;
        }

        $params['base_info']['nns_name'] = str_replace('//', '/', $params['base_info']['nns_name']);
        $params['base_info']['nns_name'] = str_replace('\\', '/', $params['base_info']['nns_name']);
        //栏目允许注入第三方栏目信息ID
        $arr_import = array(
            'nns_import_category_id' => isset($params['base_info']['nns_import_category_id']) && strlen($params['base_info']['nns_import_category_id']) >0 ? $params['base_info']['nns_import_category_id'] : '',
            'nns_import_parent_category_id' => isset($params['base_info']['nns_import_parent_category_id']) && strlen($params['base_info']['nns_import_parent_category_id']) >0 ? $params['base_info']['nns_import_parent_category_id'] : '',
        );
        //播控定义父级栏目按照cp区分，cp名即为父级
        $parent_category_name = $result_cp['data_info']['nns_name'];

        //定义父级栏目ID
        $str_parent_category_id = '10000';
        //添加获取父级栏目信息
        $depot_parent_info = $this->set_depot_category($parent_category_name, $params['base_info']['nns_type'], $str_parent_category_id);
        if ($depot_parent_info['ret'] != NS_CDS_SUCCE)
        {
            return $depot_parent_info;
        }
        $parent_category_id = $depot_parent_info['data_info']['base_info']['nns_id'];

        //添加获取新建栏目信息
        $depot_info = $this->set_depot_category($params['base_info']['nns_name'], $params['base_info']['nns_type'], $parent_category_id, $arr_import);
        $this->write_message_info($depot_info);
        return $depot_info;
    }

    /**
     * @param $str_category_name //栏目名称
     * @param int $int_depot_type //栏目类型，点播还是直播
     * @param string $str_parent_id //父级id
     * @return array  //
     */
    private function set_depot_category($str_category_name, $int_depot_type = 0, $str_parent_id = "", $arr_import = array())
    {
        $obj_re = array();

        if(empty($str_category_name) && strlen($str_category_name) <= 0)
        {
            return self::return_data(NS_CDS_FAIL, '资源库栏目名称为空');
        }

        //查询媒资库信息
        $arr_depot_ret = \nl_depot::get_depot_info(\m_config::get_dc(), array('nns_type' => $int_depot_type));
        if ($arr_depot_ret['ret'] != NS_CDS_SUCCE || !is_array($arr_depot_ret['data_info']) || count($arr_depot_ret['data_info']) < 1)
        {
            return self::return_data(NS_CDS_FAIL, 'func[set_depot_category]查询栏目信息失败');
        }
        $str_org_id = $arr_depot_ret['data_info'][0]['nns_org_id'];
        $str_depot_id = $arr_depot_ret['data_info'][0]['nns_id'];
        $import_category_id = isset($arr_import['nns_import_category_id']) ? $arr_import['nns_import_category_id'] : '';
        $import_parent_category_id = isset($arr_import['nns_import_parent_category_id']) ? $arr_import['nns_import_parent_category_id'] : '';

        //如果父级栏目不为空
        if(!empty($str_parent_id) || strlen($str_parent_id) > 0)
        {
            //根栏目的父级栏目默认为0
            $str_parent_id_2 = $str_parent_id == '10000' ? '0' : $str_parent_id;
            $arr_where = array(
                'nns_type' => $int_depot_type,
                'nns_name' => $str_category_name,
                'nns_parent_id' => $str_parent_id_2,
            );
        }
        else
        {
            $arr_where = array('nns_type' => $int_depot_type,'nns_name' => $str_category_name);
            $str_parent_id_2 = $arr_where['nns_parent_id'];
            $str_parent_id = $str_parent_id_2 == 0 ? '10000' : $str_parent_id_2;
        }

        //存在第三方注入id时
        if (strlen($import_category_id) > 0 || strlen($import_category_id) > 0)
        {
            $arr_where = array(
                'nns_type' => $int_depot_type,
                'nns_parent_id' => $str_parent_id_2,
                'nns_import_category_id' => $import_category_id,
                'nns_import_parent_category_id' => $import_parent_category_id,
            );
        }

        //根据栏目类型和父级ID查询媒资栏目信息
        $arr_category_ret = \nl_depot_v2::query(\m_config::get_dc(), $arr_where, 'nns_category_id,nns_name,nns_parent_id,nns_depot_id,nns_org_id','nns_order desc,nns_category_id asc');

        //查询成功
        if($arr_category_ret['ret'] == NS_CDS_SUCCE)
        {
            //匹配成功
            if(!empty($arr_category_ret['data_info']) && is_array($arr_category_ret['data_info']))
            {
                $category = $arr_category_ret['data_info'][0];
                //当第三方注入时,通过注入id查询到数据
                if ($category['nns_name'] != $str_category_name)
                {//当名称不一样时，修改名称
                    $st = nl_depot_v2::edit(\m_config::get_dc(), $category['nns_category_id'], $str_depot_id, $int_depot_type, array('nns_name' => $str_category_name),true);
                    if ($st['ret'] != NS_CDS_SUCCE)
                    {
                        return $st;
                    }
                }

                $obj_re = array(
                    'base_info' => array(
                        'nns_depot_id'   => $category['nns_depot_id'],
                        'nns_id'         => $category['nns_category_id'],
                        'nns_org_id'     => $category['nns_org_id'],
                        'nns_type'       => $int_depot_type,
                        'nns_name'       => $str_category_name,
                    )
                );
            }
            //匹配失败
            else
            {
                $category_id = $this->_get_depot_category_id($str_parent_id, $int_depot_type);
                //创建媒资栏目
                if($str_parent_id_2 != 0)
                {
                    $str_category_name = str_replace("<", "", $str_category_name);
                    $str_category_name = str_replace("/>", "", $str_category_name);
                    $str_category_name = str_replace("\"", "", $str_category_name);
                    $str_category_name = str_replace("'", "", $str_category_name);
                }
                //构建添加参数的数组
                $arr_add = array(
                    'nns_order' => 0,
                    'nns_org_id'=> $str_org_id,
                    'nns_type' => $int_depot_type,
                    'nns_depot_id' => $str_depot_id,
                    'nns_name' => $str_category_name,
                    'nns_category_id' => $category_id,
                    'nns_parent_id'=> $str_parent_id_2,
                    'nns_import_category_id'=> $import_category_id,
                    'nns_import_parent_category_id'=> $import_parent_category_id,
                );
                //执行添加SQL
                $arr_add_ret = \nl_depot_v2::add(\m_config::get_dc(), $arr_add);
                if($arr_add_ret['ret'] == NS_CDS_SUCCE)
                {
                    $obj_re = array(
                        'base_info' => array(
                            'nns_depot_id'   => $arr_add['nns_depot_id'],
                            'nns_id'         => $arr_add['nns_category_id'],
                            'nns_org_id'     => $arr_add['nns_org_id'],
                            'nns_type'       => $int_depot_type,
                            'nns_name'       => $str_category_name
                        ),
                    );
                }
                else
                {
                    return self::return_data(NS_CDS_FAIL, 'func[set_depot_category]创建媒资库栏目失败。' . $arr_add_ret['reason']);
                }
                unset($arr_add);
            }
        }
        else
        {
            return self::return_data(NS_CDS_FAIL, 'func[set_depot_category]查询媒资库栏目失败');
        }

        //删除变量，释放内存
        unset($str_parent_id_2);
        return self::return_data(NS_CDS_SUCCE, '成功', $obj_re);
    }
    
    /**
     * 生成媒资库栏目ID
     * @param string $str_parent_id   父级栏目ID
     * @param int    $int_depot_type  媒资库类型。0点播1直播
     * @return string
     * xinxin.deng 2018/12/4 16:50
     */
    private function _get_depot_category_id($str_parent_id,$int_depot_type = 0)
    {
        //查询该父级栏目下所有的一级子栏目
        $arr_child_category_ret = nl_depot_v2::query(\m_config::get_dc(),
            array(
                'nns_type' => $int_depot_type,
                'nns_parent_id' => $str_parent_id == '10000' ? '0' : $str_parent_id,
            ),'nns_category_id','nns_order desc,nns_category_id asc');

        $arr_child_category = np_array_rekey($arr_child_category_ret['data_info'],'nns_category_id');

        $category_id = $str_parent_id ."000";
        //生成栏目ID
        $i = 1;
        while($i < 1000)
        {
            $category_id = $str_parent_id . sprintf("%03d",$i);
            if (!array_key_exists($category_id, $arr_child_category))
            {
                break;
            }
            $i++;
        }

        return $category_id;
    }

    public function delete()
    {
        #TODO
    }

    /**
     * 查询栏目数据
     * @param array $array_query 条件数据 不能为空
     * @return array('ret'=>'状态码',
     *               'reason'=>'原因',
     *               'data_info'=> array ( 'nns_id',
     *                                      'nns_name',
     *                                      'nns_category_id' => '',
     *                                      'nns_parent_id' => '',
     *                                      'nns_import_category_id' => '',
     *                                      'nns_import_parent_category_id' => '',
     *                                      'nns_depot_id' => '',
     *                                      'nns_org_id' => '',
     *                                      'nns_order' => '',
     *                                      'nns_type' => '',
     *                                      'nns_create_time' => '',
     *                                      'nns_modify_time' => '',
     *                                      'nns_parent_name' => '',))
     */
    public function query($array_query)
    {
        $result_category = \nl_depot_v2::query_by_condition(\m_config::get_dc(), $array_query['base_info']);
        unset($array_query['base_info']['nns_video_type']);
        if($result_category['ret'] != NS_CDS_SUCCE)
        {
            return $result_category;
        }
        if(!isset($result_category['data_info']) || empty($result_category['data_info']) || !is_array($result_category['data_info']))
        {
            return self::return_data(0,'查询栏目为空');
        }
        $last_category = $result_category['data_info'];

        //将所有cp查询出来
        $cp_arr = \nl_cp::query_all(\m_config::get_dc());
        if($cp_arr['ret'] != NS_CDS_SUCCE)
        {
            return $cp_arr;
        }
        if(!isset($cp_arr['data_info']) || empty($cp_arr['data_info']) || !is_array($cp_arr['data_info']))
        {
            return self::return_data(0,'查询栏目,查询cp信息为空');
        }

        $last_cp_arr = array();
        foreach ($cp_arr['data_info'] as $value)
        {
            $last_cp_arr[$value['nns_id']] = $value['nns_name'];
        }

        //新版播控资源库栏目只有三级，第二级为cp名称，因为按cp来区分的
        foreach ($last_category as &$items)
        {
            if (isset($last_cp_arr[$items['nns_cp_id']]) && !empty($last_cp_arr[$items['nns_cp_id']]) && is_array($last_cp_arr[$items['nns_cp_id']]))
            {
                $items['nns_parent_name'] = $last_cp_arr[$items['nns_cp_id']];
            }
            else
            {
                $items['nns_parent_name'] = '';
            }
        }

        return self::return_data(0,'OK',$last_category);
    }

    /**
     * 查询运营商 信息
     */
    private function query_carrier()
    {
        $result_carrier = nl_carrier::query_all(m_config::$obj_dc);
        if($result_carrier['ret'] !=0)
        {
            return $result_carrier;
        }
        $str_reason = $result_carrier['reason'];
        $result_carrier = (isset($result_carrier['data_info'][0]) && is_array($result_carrier['data_info'][0]) && !empty($result_carrier['data_info'][0])) ? $result_carrier['data_info'][0] : null;
        if(empty($result_carrier))
        {
            return self::return_data(1,'查询运营商数据 不存在');
        }
        return self::return_data(0,$str_reason,$result_carrier);
    }
}